package com.yangli.leecode.b;

import java.util.Stack;

/**
 * @author ly
 * @description https://leetcode-cn.com/problems/valid-parentheses/
 * @data 2022/4/29
 */
public class IsValid {
    public static void main(String[] args) {
        IsValid isValid = new IsValid();
        System.out.println(isValid.isValid("{[]}"));
    }

    public boolean isValid(String s) {
        char[] chars = s.toCharArray();
        int left = 0, right = chars.length - 1;
        while (left < right) {
            if (!compare(chars[left], chars[right])) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }

    public boolean compare(char a, char b) {
        if (a == '{') {
            return b == '}';
        }
        if (a == '[') {
            return b == ']';
        }
        if (a == '(') {
            return b == ')';
        }
        return false;
    }

    public boolean isValid2(String s) {
        char[] chars = s.toCharArray();
        int length = chars.length;
        if(length%2!=0){
            return false;
        }
        Stack<Character> stack=new Stack<Character>();
        for(char c:chars) {//
                if(c=='(')
                    stack.push(')');
                else if(c=='{')
                    stack.push('}');
                else if(c=='[')
                    stack.push(']');
                else if(stack.empty()||c!=stack.pop())
                    return false;
        }
        if(stack.empty())
            return true;
        return false;
    }
}
